function [p, px, py] = pairs(m)
% pairs  - returns the pairs of values in a vector/matrix
%
% FORMAT:       [p, px, py] = pairs(matrix)
%
% Input fields:
%
%       matrix      vector or matrix (pairs taken along column dim)
%
% Output fields
%
%       p           all possible pairs (in third dim)
%       px, py      indices to get unique pairs (length: 0.5 * M * (M-1))

% Version:  v0.7f
% Build:    8111127
% Date:     Nov-11 2008, 5:27 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin ~= 1 || ...
   ~isnumeric(m) || ...
    ndims(m) > 2 || ...
    size(m, 1) < 2 || ...
    isempty(m)
    error( ....
        'BVQXtools:BadArgument', ...
        'Function pairs requires exactly one numeric, 2-d argument.' ...
    );
end

% create output of same class
s = size(m);
np = 0.5 * s(1) * (s(1) - 1);
p = m(1);
p(1) = 0;
p(np, s(2), 2) = 0;

% get nd-grid for access
[px, py] = meshgrid(1:s(1)-1, 2:s(1));
px(px >= py) = 0;
py = py(px > 0);
px = px(px > 0);

% fill output
p(:, :, 1) = m(px, :);
p(:, :, 2) = m(py, :);
